package com.hksj.jetlinks.serialize;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

public class SingleValueMap<K, V> implements Map<K, V> {
    private K key;
    private V value;

    public SingleValueMap() {
    }

    public int size() {
        return this.value == null ? 0 : 1;
    }

    public boolean isEmpty() {
        return this.size() == 0;
    }

    public boolean containsKey(Object key) {
        return Objects.equals(this.key, key);
    }

    public boolean containsValue(Object value) {
        return Objects.equals(this.value, value);
    }

    public V get(Object key) {
        return Objects.equals(key, this.key) ? this.value : null;
    }

    public V put(K key, V value) {
        this.key = key;
        V old = this.value;
        this.value = value;
        return old;
    }

    public V remove(Object key) {
        if (Objects.equals(key, this.key)) {
            V old = this.value;
            this.value = null;
            return old;
        } else {
            return null;
        }
    }

    public void putAll(Map<? extends K, ? extends V> m) {
        if (m.size() > 0) {
            Map.Entry<? extends K, ? extends V> entry = (Map.Entry)m.entrySet().iterator().next();
            this.key = entry.getKey();
            this.value = entry.getValue();
        }

    }

    public void clear() {
        this.key = null;
        this.value = null;
    }

    public Set<K> keySet() {
        return this.key == null ? Collections.emptySet() : Collections.singleton(this.key);
    }

    public Collection<V> values() {
        return this.value == null ? Collections.emptySet() : Collections.singleton(this.value);
    }

    public Set<Map.Entry<K, V>> entrySet() {
        return this.key == null ? Collections.emptySet() : Collections.singleton(new Map.Entry<K, V>() {
            public K getKey() {
                return SingleValueMap.this.key;
            }

            public V getValue() {
                return SingleValueMap.this.value;
            }

            public V setValue(V value) {
                V old = SingleValueMap.this.value;
                SingleValueMap.this.value = value;
                return old;
            }
        });
    }

    public V getValue() {
        return this.value;
    }

    public K getKey() {
        return this.key;
    }
}